<template>
  <div class="wrapper">
    <FormPanel
      ref="formPanel"
      :list="inputs"
      labelWidth="150"
      :formType="type"
      :isSubmitBtn="false"
      :cols="2"
      @formChange="formChangeHandle"
    />

    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">关 闭</el-button>
      <el-button
        :loading="saveLoading"
        v-if="this.type == 'edit'"
        type="primary"
        @click="saveDialog"
      >保 存</el-button>
      <el-button
        :loading="sumbitLoading"
        v-if="this.type == 'edit'"
        type="primary"
        @click="sumbitDialog"
      >提 交</el-button>
    </div>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import { updateDealerMaterial, saveDealerMaterial, selectDealerMaterialById, update } from '@/api/cms-api/projectOperating/program/push';
export default {
  mixins: [dictionary],
  components: {},
  props: {
    type: {
      type: String,
      required: true
    },
    rowData: {
      type: Object,
      default: () => ({})
    }
  },
  async mounted() {
    // console.log(this.value);
    if (this.type === 'show') {
      if (this.rowData.id == null) {
        //反馈状态
        this.formValue = Object.assign(this.formValue, { isNeedFeedback: this.rowData.isNeedFeedback });
        this.rowData = Object.assign(this.rowData, { feedbackStatus: 25271001 });
        await saveDealerMaterial(this.rowData);
      }
    }
  },
  data() {
    return {
      inputs: this.getInputs(),
      inputsData: {},
      formValue: {},
      dataParams: {}, //父类参数
      caseUrlList: [],
      saveLoading: false,
      sumbitLoading: false
    };
  },
  created() {
    this.init();
  },
  methods: {
    //保存
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      if (null == this.$refs.formPanel.SUBMIT_FORM()) {
        return;
      }
      if (this.formValue !== null) {
        this.saveLoading = true;
        if (this.type === 'edit') {
          let result = {};
          if (this.formValue.caseUrl != null) {
            for (let i = 0; i < this.formValue.caseUrl.length; i++) {
              this.caseUrlList.push(Object.assign({}, { name: this.formValue.caseUrl[i].name }, { url: this.formValue.caseUrl[i].url }));
            }
            this.formValue = Object.assign({}, { fileUrl: this.caseUrlList }, this.formValue);
          }
          this.formValue = Object.assign({}, { materialId: this.rowData.materialId }, this.formValue);
          // this.formValue = Object.assign({}, { dealerId: this.rowData.dealerId }, this.formValue);
          this.formValue = Object.assign({}, { sourceDept: this.rowData.sourceDept }, this.formValue);
          this.formValue = Object.assign({}, { dealerCode: this.rowData.dealerCode }, this.formValue);
          this.formValue = Object.assign(this.formValue, { dealerName: this.rowData.dealerName });
          this.formValue = Object.assign(this.formValue, { isNeedFeedback: this.rowData.isNeedFeedback });
          if (this.id == null) {
            //新增反馈
            this.formValue = Object.assign(this.formValue, { feedbackStatus: 25271001 });
            console.log(this.formValue);
            result = await saveDealerMaterial(this.formValue);
            if (result.resultCode === 200) {
              this.saveLoading = false;
              this.$notify.success({ title: '提示信息', message: '保存成功!' });
              this.closeDialog('refresh');
            }
          } else {
            //如果id不为null，根据id查询是否被查看，如果被查看则走原始update,否则走自定义的update
            let res = await selectDealerMaterialById(this.rowData.id);
            if (res.resultCode === 200) {
              //是否首次被查看
              if (res.data.isView == null) {
                //是首次查看
                result = await updateDealerMaterial(this.formValue, this.rowData.id);
                if (result.resultCode === 200) {
                  this.saveLoading = false;
                  this.$notify.success({ title: '提示信息', message: '保存成功!' });
                  this.closeDialog('refresh');
                }
              } else {
                result = await update(this.formValue, this.rowData.id);
                if (result.resultCode === 200) {
                  this.saveLoading = false;
                  this.$notify.success({ title: '提示信息', message: '保存成功!' });
                  this.closeDialog('refresh');
                }
              }
            }
            // result = await updateDealerMaterial(this.formValue, this.rowData.id);
            // if (result.resultCode === 200) {
            //   this.saveLoading = false;
            //   this.$notify.success({ title: '提示信息', message: '保存成功!' });
            //   this.closeDialog('refresh');
            // }
          }
        }
      }
    },
    //提交
    async sumbitDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      if (null == this.$refs.formPanel.SUBMIT_FORM()) {
        return;
      }
      if (this.formValue !== null) {
        this.sumbitLoading = true;
        if (this.type === 'edit') {
          let result = {};
          if (this.formValue.caseUrl != null) {
            for (let i = 0; i < this.formValue.caseUrl.length; i++) {
              this.caseUrlList.push(Object.assign({}, { name: this.formValue.caseUrl[i].name }, { url: this.formValue.caseUrl[i].url }));
            }
            this.formValue = Object.assign({}, { fileUrl: this.caseUrlList }, this.formValue);
          }
          this.formValue = Object.assign({}, { materialId: this.rowData.materialId }, this.formValue);
          // this.formValue = Object.assign({}, { dealerId: this.rowData.dealerId }, this.formValue);
          this.formValue = Object.assign({}, this.formValue, { feedbackStatus: 25271002 });
          this.formValue = Object.assign({}, { sourceDept: this.rowData.sourceDept }, this.formValue);
          this.formValue = Object.assign({}, { dealerCode: this.rowData.dealerCode }, this.formValue);
          this.formValue = Object.assign(this.formValue, { dealerName: this.rowData.dealerName });
          this.formValue = Object.assign(this.formValue, { isNeedFeedback: this.rowData.isNeedFeedback });
          if (this.id == null) {
            //新增反馈
            result = await saveDealerMaterial(this.formValue);
            if (result.resultCode === 200) {
              this.sumbitLoading = false;
              this.$notify.success({ title: '提示信息', message: '提交成功!' });
              this.closeDialog('refresh');
            }
          } else {
            //如果id不为null，根据id查询是否被查看，如果被查看则走原始update,否则走自定义的update
            let res = await selectDealerMaterialById(this.rowData.id);
            if (res.resultCode === 200) {
              //是否首次被查看
              if (res.data.isView == null) {
                //是首次查看
                result = await updateDealerMaterial(this.formValue, this.rowData.id);
                if (result.resultCode === 200) {
                  this.sumbitLoading = false;
                  this.$notify.success({ title: '提示信息', message: '提交成功!' });
                  this.closeDialog('refresh');
                }
              } else {
                result = await update(this.formValue, this.rowData.id);
                if (result.resultCode === 200) {
                  this.sumbitLoading = false;
                  this.$notify.success({ title: '提示信息', message: '提交成功!' });
                  this.closeDialog('refresh');
                }
              }
            }
            // result = await updateDealerMaterial(this.formValue, this.rowData.id);
            // if (result.resultCode === 200) {
            //   this.sumbitLoading = false;
            //   this.$notify.success({ title: '提示信息', message: '提交成功!' });
            //   this.closeDialog('refresh');
            // }
          }
        }
      }
    },
    formatDates: function(value) {
      // 这里的 value 就是需要过滤的数据
      if (value == null || value == '') {
        return '';
      }
      var date = new Date(value);
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      return year + '-' + month + '-' + day;
    },
    init() {
      if (this.type === 'edit') {
        this.id = this.rowData.id;
        this.inputs[11].placeholder = '请选择';
        this.inputs[12].placeholder = '请输入';
        this.inputs.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
          if (x.fieldName == 'feedbackCode') {
            //反馈编号
            if (x.initialValue == null) {
              x.initialValue = 'MR' + this.rowData.dealerCode + this.rowData.materialCode.substring(2);
            }
          }
          if (x.fieldName == 'feedbackStatus') {
            //反馈状态
            if (x.initialValue == null) {
              x.initialValue = '未提报';
            }
          }
        });
      }
      if (this.type === 'show') {
        this.materialId = this.rowData.materialId;
        this.materialStatus = this.rowData.materialStatus;
        // console.log(this.rowData);
        this.inputs.forEach(x => {
          x.initialValue = this.rowData[x.fieldName];
          if (x.fieldName == 'feedbackCode') {
            //反馈编号
            if (x.initialValue == null) {
              x.initialValue = 'MR' + this.rowData.dealerCode + this.rowData.materialCode.substring(2);
            }
          }
          if (x.fieldName == 'feedbackStatus') {
            //反馈状态
            if (x.initialValue == null) {
              x.initialValue = '未提报';
            }
          }
        });
      }
    },
    formChangeHandle(val) {
      this.formValue = val;
    },
    getInputs() {
      return [
        {
          type: 'INPUT',
          label: '反馈编号',
          disabled: true,
          fieldName: 'feedbackCode',
          initialValue: '',
          placeholder: '系统自动生成'
        },
        // {
        //   type: 'INPUT',
        //   label: '来源部门',
        //   disabled: true,
        //   fieldName: 'sourceDept',
        //   initialValue: ''
        // },
        {
          type: 'INPUT',
          label: '来源部门',
          disabled: true,
          fieldName: 'deptName',
          initialValue: '',
          placeholder: ''
        },
        {
          type: 'SELECT',
          label: '反馈状态',
          disabled: true,
          fieldName: 'feedbackStatus',
          placeholder: '',
          initialValue: '',
          itemList: this.createDictList('2527')
        },
        // {
        //   type: 'INPUT',
        //   label: '经销商代码',
        //   disabled: true,
        //   fieldName: 'dealerCode',
        //   initialValue: ''
        // },
        // {
        //   type: 'INPUT',
        //   label: '经销商名称',
        //   disabled: true,
        //   fieldName: 'dealerName',
        //   initialValue: ''
        // },
        {
          type: 'INPUT',
          label: '营销素材代码',
          disabled: true,
          fieldName: 'materialCode',
          placeholder: '系统自动生成',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '营销素材名称',
          disabled: true,
          fieldName: 'materialName',
          placeholder: '请输入...',
          initialValue: ''
          // rules: [{ required: true, message: '请输入营销素材名称', trigger: 'blur' }]
        },
        {
          type: 'DATE',
          label: '反馈截止日期',
          disabled: true,
          fieldName: 'feedbackEndDate',
          valueFormat: 'yyyy-MM-dd',
          placeholder: '',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '营销素材类型-一级',
          disabled: true,
          fieldName: 'materialTypeOneName',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '营销素材类型-二级',
          disabled: true,
          fieldName: 'materialTypeTwoName',
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '营销素材类型-三级',
          disabled: true,
          fieldName: 'materialTypeThreeName',
          initialValue: '',
          placeholder: ''
        },
        {
          type: 'INPUT',
          label: '营销素材类型-四级',
          disabled: true,
          fieldName: 'materialTypeFourName',
          initialValue: '',
          placeholder: ''
        },
        {
          type: 'INPUT',
          label: '营销素材类型-五级',
          disabled: true,
          fieldName: 'materialTypeFiveName',
          initialValue: '',
          placeholder: ''
        },
        {
          type: 'SELECT',
          label: '反馈结果',
          fieldName: 'feedbackResult',
          initialValue: '',
          placeholder: '',
          change: this.isAllChange,
          itemList: this.createDictList('2575'),
          rules: [{ required: true, message: '请选择反馈结果', trigger: 'change' }]
        },
        {
          type: 'INPUT',
          label: '审核人',
          fieldName: 'reviewPersonName',
          placeholder: '',
          initialValue: '',
          selfCols: 2,
          disabled: true
        },
        {
          type: 'TEXT_AREA',
          label: '审核意见',
          fieldName: 'reviewIdea',
          placeholder: '',
          initialValue: '',
          selfCols: 2,
          disabled: true
        },
        {
          type: 'TEXT_AREA',
          label: '反馈描述',
          fieldName: 'feedbackDesc',
          initialValue: '',
          placeholder: '',
          selfCols: 2,
          maxlength: 300,
          rules: [{ max: 300, message: '反馈描述长度不能超过300', trigger: 'blur' }]
        },
        {
          type: 'UPLOAD_FILE',
          label: '附件',
          fieldName: 'caseUrl',
          selfCols: 2,
          rules: [{ required: false, message: '请上传附件', trigger: 'change' }],
          upload: {
            actionUrl: '/api/file/oss/upload'
          }
        }
      ];
    },
    changeHandle(data) {
      this.inputsData = data;
      this.$emit('close', data);
    },
    //取消操作
    closeDialog(param) {
      this.$emit('close', false, param);
    },
    //反馈结果
    isAllChange(val) {
      if (val === 25751001) {
        //制作完成反馈
        this.inputs.find(item => item.fieldName === 'caseUrl').rules[0].required = true;
      } else {
        //未制作反馈
        this.inputs.find(item => item.fieldName === 'caseUrl').rules[0].required = false;
        this.$refs.formPanel.$refs.form.clearValidate();
      }
    }
  }
};
</script>
<style scoped>
.wrapper {
  height: calc(100vh - 110px);
}
</style>
